<template>
  <div class="login-container">
    <!-- 登录对话框 -->
    <el-dialog title="登录" :visible.sync="dialogVisible" width="500px" height="400px" class="dialog-login"
               :before-close="handleClose">
      <!-- 登录表单内容 -->
      <el-form ref="userForm" :model="loginForm" :rules="rules" label-width="70px" class="login-form">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="loginForm.email" autocomplete="off" placeholder="请输入邮箱" prefix-icon="el-icon-user"
                    style="width: 300px"></el-input>
        </el-form-item>
        <!-- 密码输入框，仅在密码登录时显示 -->
        <el-form-item v-if="loginType === 'password'" label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" prefix-icon="el-icon-lock"
                    style="width: 300px" autocomplete="off"></el-input>
          <!-- 忘记密码链接 -->
          <div class="forget-password" @click="handleForgetPassword">忘记密码？</div>
        </el-form-item>
        <!-- 验证码输入框，仅在验证码登录时显示 -->
        <el-form-item v-if="loginType === 'verification'" label="验证码" prop="code">
          <el-input placeholder="请输入验证码" v-model="loginForm.code" prefix-icon="el-icon-chat-round"
                    style="width: 300px" autocomplete="off">
            <template #append>
              <el-button :disabled="countdown > 0" @click="sendVerificationCode()" size="small">
                {{ countdown > 0 ? `${countdown} 秒` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <!-- 同意协议复选框 -->
        <el-form-item>
          <el-checkbox v-model="agreement">我已阅读并同意<a href="your-agreement-link" target="_blank">《用户协议》</a>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-btn">登录</el-button>
        </el-form-item>
        <!-- 切换登录方式的链接 -->
        <div @click="toggleLoginType" class="toggle-login-type">
          {{ loginType === 'password' ? '使用验证码登录' : '使用密码登录' }}
        </div>
      </el-form>
    </el-dialog>


    <el-dialog title="注册" :visible.sync="forgetPasswordDialogVisible" width="500px" height="400px"
               class="dialog-register"
               :before-close="handleClose">
      <!-- 登录表单内容 -->
      <el-form ref="userForm" :model="resetForm" :rules="rules" label-width="80px" class="register-form">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="resetForm.email" autocomplete="off" placeholder="请输入邮箱" prefix-icon="el-icon-user"
                    style="width: 300px"></el-input>
        </el-form-item>
        <!-- 密码输入框，仅在密码登录时显示 -->
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="resetForm.password" placeholder="请输入新新密码" prefix-icon="el-icon-lock"
                    style="width: 300px" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="resetForm.confirmPassword" placeholder="请再次输入密码"
                    prefix-icon="el-icon-lock" style="width: 300px" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 验证码输入框，仅在验证码登录时显示 -->
        <el-form-item label="验证码" prop="code">
          <el-input placeholder="请输入验证码" v-model="resetForm.code" prefix-icon="el-icon-chat-round"
                    style="width: 300px" autocomplete="off">
            <template #append>
              <el-button :disabled="countdown > 0" @click="sendCode()" size="small">
                {{ countdown > 0 ? `${countdown} 秒` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleUpdate" class="login-btn">确定</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>


<script>
export default {

  data() {
    return {
      forgetPasswordDialogVisible: false,
      dialogVisible: false, // 控制对话框显示与隐藏
      loginForm: {
        email: '',
        password: '',
        code: '' // 添加验证码字段
      },
      resetForm: { // 存储重置密码表单的数据
        email: '',
        password: '',
        code: '',
        confirmPassword: ''
      },
      loginType: 'password', // 控制登录类型
      countdown: 0, // 添加倒计时初始值
      agreement: false, // 同意协议的状态
      rules: {
        email: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {len: 6, message: '验证码长度为 6 个字符', trigger: 'blur'}
        ],
      },
    }
  },
  methods: {
    validateEmail(email) {
      const regex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      return regex.test(email);
    },
    handleLogin() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {  // 表单校验合法
          if (!this.agreement) {
            this.$message({
              message: '请先阅读并同意用户协议',
              type: 'warning'
            });
            return;
          }
          if (!this.validateEmail(this.loginForm.email)) {
            this.$message.error('请输入有效的邮箱');
          }
          // 根据 loginType 处理不同的登录逻辑
          if (this.loginType === 'password') {
            this.request.post('/user/front/loginPassword', this.loginForm)
                .then(res => {
                  if (res.code === 400) {
                    this.$message.error(res.message);
                  } else if (res.code === 200) {
                    this.dialogVisible = false
                    this.$message.success(res.message);
                    this.$store.dispatch('loginSuccess', {user: res.user, token: res.token});
                    this.loginForm = {}
                    this.agreement = false

                  }
                })
          } else {
            this.request.post('/user/front/loginCode', this.loginForm)
                .then(res => {
                  if (res.code === 400) {
                    this.$message.error(res.message);
                  } else if (res.code === 200) {
                    this.dialogVisible = false
                    this.$message.success(res.message);
                    this.$store.dispatch('loginSuccess', {user: res.user, token: res.token});
                    this.agreement = false
                    this.loginForm = {}
                  }
                })
          }


        } else {
          return false;
        }
      });


    },
    toggleLoginType() {
      this.loginType = this.loginType === 'password' ? 'verification' : 'password';
    },
    startCountdown() {
      if (this.countdown > 0) return; // 如果已经在倒计时中，则不再重新开始

      this.countdown = 60; // 假设倒计时60秒
      const intervalId = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(intervalId);
        }
      }, 1000);
    },
    handleClose(done) {
      this.dialogVisible = false; // 关闭对话框
      this.$nextTick(() => {
        this.$refs['userForm'].resetFields(); // 重置表单字段
        this.resetForm = {}; // 清空表单数据
        this.countdown = 0; // 重置验证码倒计时
        this.agreement = false
        done(); // 关闭对话框
      });
    },
    sendVerificationCode() {
      // 向后端发送请求获取验证码
      this.request.get('/mail/front/sendLoginCode/' + this.loginForm.email)
          .then(response => {
            if (response.code === 200) {
              this.startCountdown();
              this.$message.success(response.message)
            } else if (response.code === 400) {
              this.$message.error(response.message)

            }
          })
          .catch(error => {
            console.error('发送验证码失败', error);
          });
    },
    handleUpdate() {

      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          if (this.resetForm.password !== this.resetForm.confirmPassword) {
            this.$message.error('两次密码输入不一致');
          } else {
            this.request.post('/user/front/forgetPassword', this.resetForm)
                .then(res => {
                  if (res.code === 400) {
                    this.$message.error(res.message)
                  } else if (res.code === 200) {
                    this.$message.success(res.message)
                    this.forgetPasswordDialogVisible = false
                  }
                })
          }


        }

      })

    },
    handleForgetPassword() {
      this.dialogVisible = false;
      this.forgetPasswordDialogVisible = true
    },
    sendCode() {
      this.request.get('/mail/front/sendLoginCode/' + this.resetForm.email)
          .then(response => {
            console.log(response)
            if (response.code === 200) {
              this.startCountdown();
              this.$message.success(response.message)
            } else if (response.code === 400) {
              this.$message.error(response.message)

            }
          })
          .catch(error => {
            console.error('发送验证码失败', error);
          });
    }
  }
}
</script>
<style scoped>


.toggle-login-type {
  cursor: pointer;
  color: #409EFF;
  margin-top: 10px;
  text-align: center;
}


.dialog-login {
  border-radius: 10px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
}


.login-form {
  padding: 20px;
}

.login-btn {
  padding: 10px 0;
  border-radius: 5px;
  font-size: 16px;
  background-color: #409EFF;
  border-color: #409EFF;
  width: 200px;
  transition: background-color .3s, border-color .3s;
  margin-left: 35px;
}

.login-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.toggle-login-type {
  cursor: pointer;
  color: #409EFF;
  margin-top: 10px;
  text-align: center;
  font-size: 14px;
  transition: color .3s;
}

.toggle-login-type:hover {
  color: #66b1ff;
}

.forget-password {
  color: #409EFF;
  cursor: pointer;
  margin-top: 5px;
  font-size: 14px;
  transition: color .3s;
  margin-left: 235px;
}

.forget-password:hover {
  color: #66b1ff;
}


</style>